package cn.example.vip.mall.page.service.impl;

import cn.example.vip.mall.page.service.SeckillPageService;
import cn.example.vip.mall.seckill.entity.SeckillGoods;
import cn.example.vip.mall.seckill.feign.SeckillGoodsFeign;
import cn.example.vip.mall.util.RespResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class SeckillPageServiceImpl implements SeckillPageService {
	@Autowired
	TemplateEngine templateEngine;
	@Value("${seckillItems.pagepath}")
	private String pagepath;
	@Autowired
	private SeckillGoodsFeign seckillGoodsFeign;
	
	@Override
	public void html(String id) throws Exception {
		
		// 1.创建容器对象(上下文对象)
		Context context = new Context();
		// 2.设置模板数据
		context.setVariables(loadData(id));
		// 3.指定文件生成后的存储路径
		File file = new File(pagepath, id + ".html");
		
		// 获取类加载器
//		ClassLoader classLoader = PageServiceImpl.class.getClassLoader();
		// 获取资源文件所在目录的路径
//		String path = classLoader.getResource("static").getPath();
		// 创建文件对象
//		File file = new File(path + "/" + id + ".html");
		try {
			// 创建新文件
			if (file.createNewFile()) {
				System.out.println("文件创建成功：" + file.getAbsolutePath());
			} else {
				System.out.println("文件已存在：" + file.getAbsolutePath());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		PrintWriter writer = new PrintWriter(file, "UTF-8");
		// 4.执行合成生成
		templateEngine.process("seckillitem", context, writer);
	}
	
	@Override
	public void delHtml(String id) {
		// 3.指定文件生成后的存储路径
		File file = new File(pagepath, id + ".html");
		
		// 获取类加载器
//		ClassLoader classLoader = PageServiceImpl.class.getClassLoader();
		// 获取资源文件所在目录的路径
//		String path = classLoader.getResource("static").getPath();
		// 创建文件对象
//		File file = new File(path + "/" + id + ".html");
		
		// 获取路径
//		File file = new File(pagepath + spuId + ".html");
		// 删除文件
		if(file.exists()){
			file.delete();
		}
	}
	
	/**
	 * 加载数据
	 */
	public Map<String, Object> loadData(String id){
		// 加载数据
		RespResult<SeckillGoods> respResult = seckillGoodsFeign.queryBySeckillId(id);
		if(respResult.getData() != null){
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("item", respResult.getData());
			dataMap.put("images", respResult.getData().getImages().split(","));
			return dataMap;
		}
		return null;
	}
	
}
